# 用方向键控制方块移动
# 方向键松开, 停止移动
# Nasa 20211003
import pygame
import sys


def move():
    pygame.init()
    winx = 150
    winy = 150
    screen = pygame.display.set_mode((winx, winy))
    fclock = pygame.time.Clock()
    xl = 51
    yl = 51
    speedx = 5
    speedy = 5
    b = 'still'
    while True:
        screen.fill((0, 0, 0))
        r2 = pygame.Rect(10,20,10,10)
        pygame.draw.rect(screen,(255,0,255),r2)
        pygame.draw.rect(screen,
                         (255, 255, 255),
                         (xl, yl, 20, 25))
        r1 = pygame.Rect(xl, yl, 20, 25)
        if pygame.Rect.colliderect(r1, r2):
            print('collide')
        if b == 'down':
            yl += speedy
        elif b == 'up':
            yl -= speedy
        elif b == 'left':
            xl -= speedx
        elif b == 'right':
            xl += speedx

        if xl + 20 < 0:
            xl = winx
        elif xl > winx:
            xl = -20
        if yl + 20 < 0:
            yl = winy
        elif yl > winy:
            yl = -20

        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if e.type == pygame.KEYDOWN:
                if e.key == pygame.K_DOWN:
                    b = 'down'
                elif e.key == pygame.K_UP:
                    b = 'up'
                elif e.key == pygame.K_LEFT:
                    b = 'left'
                elif e.key == pygame.K_RIGHT:
                    b = 'right'
            elif e.type == pygame.KEYUP:
                if e.key in [pygame.K_DOWN, pygame.K_UP, pygame.K_RIGHT, pygame.K_LEFT]:
                    b = 'still'
        pygame.display.update()
        fclock.tick(10)


if __name__ == '__main__':
    move()
